<template>
  <div>
    <Breadcrumb :opt-data="protocolOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable v-loading="tableLoading" :table-id="tableId" :table-hdl="tableHdl" :rows="protocolData"
                 :custom-empty="true" @pageChanged="getProtocolData" @sizeChanged="getProtocolData"
                 @filterChange="getProtocolData">
          <EmptyContent slot="empty" :opt-data="protocolOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog :title="formTitle" :visible.sync="showProtocolDialog"  :close-on-click-modal="false" width="680px" center>
        <el-form v-loading="protocolFormLoading" :ref="protocolFormRef" :model="protocolForm" :rules="protocolFormRules"
                 size="small" label-width="130px">
          <el-form-item label="协议名称" prop="protocolName">
            <el-input v-model="protocolForm.protocolName" placeholder="请填写协议名称"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="链路类型" prop="linkTypes">
                <el-select v-model="protocolForm.linkTypes" clearable filterable class="width-100" multiple
                           collapse-tags
                           placeholder="请选择链路类型"
                           @change="linkTypeChanged">
                  <el-option :label="link.label" :value="link.value" :key="idx"
                             v-for="(link, idx) in linkTypeData"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传输协议">
                <el-select v-model="protocolForm.protocolType" clearable filterable class="width-100"
                           placeholder="请选择传输协议">
                  <el-option label="无" value=""></el-option>
                  <el-option :label="protocol.label" :value="protocol.value" :key="idx"
                             v-for="(protocol, idx) in protocolTypeData"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备类别" prop="deviceType">
                <el-select v-model="protocolForm.deviceType" clearable filterable class="width-100"
                           placeholder="请选择设备类别" @change="deviceTypeChanged">
                  <el-option :label="deviceType.label" :value="deviceType.value" :key="idx"
                             v-for="(deviceType, idx) in deviceTypeData"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备厂家" prop="manufacturer">
                <el-select v-model="protocolForm.manufacturer" clearable filterable class="width-100"
                           placeholder="请选择设备厂家">
                  <el-option :label="manufacturer.label" :value="manufacturer.value" :key="idx"
                             v-for="(manufacturer, idx) in manufacturerData"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联通用协议" prop="generalProtocolId">
                <el-select v-model="protocolForm.generalProtocolId" clearable filterable class="width-100"
                           placeholder="请选择通用协议" :disabled="isEditProtocol && protocolForm.generalProtocolId">
                  <el-option :label="protocolType.protocolName" :value="protocolType._id" :key="idx"
                             v-for="(protocolType, idx) in generalProtocolData"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="protocolForm.protocolType==='MQTT'">
              <el-form-item label="协议版本" >
                <el-select v-model="protocolForm.protocolVersion" clearable filterable class="width-100"
                           placeholder="请选择协议版本" >
                  <el-option :label="proVersion.label" :value="proVersion.value" :key="idx"
                             v-for="(proVersion, idx) in protocolVersionData"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="协议标识">
                <el-radio-group v-model="protocolForm.protocolMark">
                  <el-radio :label="protocol.value" :key="idx" v-for="(protocol, idx) in commonConfig.protocolMark">
                    {{protocol.label}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>


          </el-row>
          <el-tabs v-model="activeName" type="border-card" class="tab-box"
                   v-if="protocolForm.protocolParams && protocolForm.protocolParams.length>0">
            <el-tab-pane v-for="(item,index) in protocolForm.protocolParams" :key="index" :label="item.linkTypeName"
                         :name="item.linkTypeName">
              <div v-if="item.linkTypeName === commonConfig.linkType[0].value
          || item.linkTypeName === commonConfig.linkType[1].value">
                <el-form-item label="端口号">
                  <el-input-number class="width-50" v-model="item.port" :min="0"></el-input-number>
                </el-form-item>
              </div>
              <div
                v-if="item.linkTypeName === commonConfig.linkType[2].value || item.linkTypeName === commonConfig.linkType[5].value">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="默认接收端口">
                      <el-input-number class="width-100" v-model="item.defaultReceivePort"
                                       :min="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="默认发送端口">
                      <el-input-number class="width-100" v-model="item.defaultSendPort"
                                       :min="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <div v-if="item.linkTypeName === commonConfig.linkType[3].value">
                <!--            <el-form-item label="端口号">-->
                <!--              <el-input-number class="width-100" v-model="protocolForm.protocolParam.port" :min="0"></el-input-number>-->
                <!--            </el-form-item>-->
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="波特率">
                      <el-select v-model="item.baudRate" clearable filterable class="width-100"
                                 placeholder="请选择波特率">
                        <el-option :label="baudRate.label" :value="baudRate.value" :key="idx"
                                   v-for="(baudRate, idx) in commonConfig.baudRate"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="奇偶校验位">
                      <el-select v-model="item.parity" clearable filterable class="width-100"
                                 placeholder="请选择奇偶校验位">
                        <el-option :label="parity.label" :value="parity.value" :key="idx"
                                   v-for="(parity, idx) in commonConfig.parity"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="通讯位位数">
                      <el-input-number class="width-100" v-model="item.dataBitLen"
                                       :min="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="停止位位数">
                      <el-input-number class="width-100" v-model="item.stopBitLen"
                                       :min="0"></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-tab-pane>
          </el-tabs>
          <el-form-item label="数据采集方式">
            <el-radio-group v-model="protocolForm.collectWay">
              <el-radio :label="collect.value" :key="idx" v-for="(collect, idx) in commonConfig.collectType">
                {{collect.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="最小采样周期(ms)">
            <el-input-number class="width-50" v-model="protocolForm.minCollectInterval" :min="0"
                             :step="100"></el-input-number>
          </el-form-item>
          <el-form-item label="离线重连间隔(ms)">
            <el-input-number class="width-50" v-model="protocolForm.retryInterval" :min="0"
                             :step="100"></el-input-number>
          </el-form-item>
          <div v-if="protocolForm.specialConfig" style="padding-left: 55px">
            <el-collapse class="mar-top mar-btm">
              <el-collapse-item name="special-char-setting">
                <template slot="title">
                  <div class="el-form-item__label font-color-warning font-weight-bold"><span>协议特殊标志殊符设置</span>
                  </div>
                </template>
                <el-form v-loading="protocolFormLoading" :ref="protocolFormRef" :model="protocolForm"
                         :rules="protocolFormRules" size="small" label-position="top">
                  <div class="header6">地址符设置</div>
                  <el-row :gutter="20" class="mar-top-5">
                    <el-col :span="12">
                      <el-form-item label="地址符开始位置">
                        <el-input-number class="width-100" v-model="protocolForm.specialConfig.addrCharStartPos"
                                         placeholder="地址符开始位置"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="地址符长度">
                        <el-input-number class="width-100" v-model="protocolForm.specialConfig.addrCharLength"
                                         placeholder="地址符长度"></el-input-number>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <div class="header6 mar-top-10">拆包设置</div>
                  <el-row :gutter="20" class="mar-top-5">
                    <el-col :span="12">
                      <el-form-item label="拆包方式">
                        <el-select v-model="protocolForm.specialConfig.unpackType" clearable filterable
                                   :allow-create="true" class="width-100" placeholder="请选择拆包方式">
                          <el-option v-for="(unpack, idx) in commonConfig.unpackType" :label="unpack.label"
                                     :value="unpack.value" :key="idx"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([1, 2])" :span="12">
                      <el-form-item label="分隔符">
                        <el-input v-model="protocolForm.specialConfig.delimiter" placeholder="请填写分隔符"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([2])" :span="12">
                      <el-form-item label="起始符">
                        <el-input v-model="protocolForm.specialConfig.startChar" placeholder="请填写起始符"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([2])" :span="12">
                      <el-form-item label="长度符开始位置">
                        <el-input-number class="width-100" v-model="protocolForm.specialConfig.lenCharStartPos"
                                         placeholder="长度符开始位置"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([2])" :span="12">
                      <el-form-item label="长度符长度">
                        <el-input-number class="width-100" v-model="protocolForm.specialConfig.lenCharLength"
                                         placeholder="长度符长度"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([2])" :span="12">
                      <el-form-item label="数据长度所使用的编码方式">
                        <el-select v-model="protocolForm.specialConfig.encodeType" clearable filterable
                                   class="width-100" placeholder="请选择编码方式">
                          <el-option v-for="(encode, idx) in commonConfig.encodeType" :label="encode.label"
                                     :value="encode.value" :key="idx"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([2])" :span="12">
                      <el-form-item label="需计算长度数据开始位置">
                        <el-input-number class="width-100" v-model="protocolForm.specialConfig.computedDataStartPos"
                                         placeholder="需计算长度数据开始位置"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col v-show="showUnpackItem([2])" :span="12">
                      <el-form-item label="终止符的相对位置">
                        <el-input-number class="width-100" v-model="protocolForm.specialConfig.terminatorRelPos"
                                         placeholder="终止符的相对位置"></el-input-number>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-collapse-item>
            </el-collapse>
          </div>
          <el-form-item label="协议版本" prop="protocolVer">
            <el-input v-model="protocolForm.protocolVer" placeholder="请填写协议版本"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="protocolForm.remarks" placeholder="请填写备注"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="protocolFormCanceled">取消</el-button>
              <el-button size="medium" type="primary" @click="protocolFormSubmitted">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
      <!--协议文档管理-->
      <el-dialog title="协议文档管理" :visible.sync="showDocumentDialog"  :close-on-click-modal="false" width="680px" center>
        <p class="flex-justify-end">
          <el-button type="primary" size="small" @click="uploadFiles">上传</el-button>
        </p>
        <el-table :data="protocolFiles" style="width: 100%" border height="400"
                  :default-sort="{ prop: 'date', order: 'descending' }">
          <el-table-column label="序号" type="index">
          </el-table-column>
          <el-table-column prop="name" label="协议文档名称" width="260">
          </el-table-column>
          <el-table-column prop="date" sortable label="上传日期" width="150">
            <template slot-scope="scope">
              {{transFormTime(scope.row.date)}}
            </template>

          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button type="default" size="mini" @click="downloadImage(scope.row)">下载
              </el-button>

              <el-button type="danger" size="mini" @click="deletFiles(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <p style="text-align:center" v-if="protocolFilesTotal > 0">共{{protocolFilesTotal}}条</p>
      </el-dialog>
      <el-dialog title="上传协议文档管理" :visible.sync="showDocumentUploadDialog" width="680px" center  :close-on-click-modal="false"
                 @close="cancelUpload"
                 v-loading="uploadLoading">
        <el-upload :auto-upload="false" ref="uploadref" drag action="action" :limit="1" :on-exceed="handleExceed"
                   accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf" :file-list="fileList" :on-remove="handleRemove"
                   :on-change="handleChange">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">doc/docx/xls/xlsx/ppt/pptx/pdf文件，且不超过50M</div>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelUpload">取 消</el-button>
          <el-button type="primary" @click="closeUpload">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="设备协议小组件"
        :visible.sync="showProtocolWidgetDialog"
        :close-on-click-modal="false"
        width="1200px"
        center>
        <GeneralProtocolWidget v-if="showProtocolWidgetDialog" :genDeviceType="curGenDeviceType" :deviceProtocolId="curDeviceProtocolId"
                               :isProtocol="false" :currentGeneralProtocolId="currentGeneralProtocolId"></GeneralProtocolWidget>
      </el-dialog>
      <el-dialog
        v-loading="relatedProtocolLoading"
        :close-on-click-modal="false"
        title="关联通用协议小组件"
        :visible.sync="showRelatedProtocolWidgetDialog"
        width="500px"
        center>
        <el-form :ref="relatedProtocolFormRef" :model="relatedProtocolForm" :rules="relatedProtocolFormRules"
                 size="medium"
                 label-width="120px">
          <el-form-item label="通用协议" prop="generalProtocolId">
            <el-select v-model="relatedProtocolForm.generalProtocolId" placeholder="请选择组件类型" class="width-100">
              <el-option :label="protocolType.protocolName" :value="protocolType._id" :key="idx"
                         v-for="(protocolType, idx) in generalProtocolData"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showRelatedProtocolWidgetDialog=false">取 消</el-button>
          <el-button type="primary" @click="relatedProtocolWidget">确 定</el-button>
        </span>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {commonConfig, componentReviewArray} from '@/config/common';
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {msgCode} from "@/config/string";
  import {confirmHandle, deepCopyWithJson, messageHandle, getUserInfo} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import protocolTableCfg from "../../config/table/protocol";
  import EZTable from '../../components/table/EZTable';
  import {routerMeta} from "@/router/routerMeta";
  import moment from "moment";
  import {momentFormat} from '@/config/ide/common';
  import {assetBaseUrl} from '@/config/env';
  import axios from "axios";
  import GeneralProtocolWidget from "@/page/relationData/generalProtocol/partial/GeneralProtocolWidget.vue";

  export default {
    name: "DeviceProtocolList",
    components: {
      GeneralProtocolWidget,
      EZTable
    },
    data() {
      return {
        commonConfig: commonConfig,
        tableLoading: true,
        tableId: tableIdConfig.protocol,
        tableHdl: null,
        protocolData: [],
        showProtocolDialog: false,
        protocolFormLoading: false,
        deviceTypeData: [],
        manufacturerData: [],
        linkTypeData: [],
        protocolTypeData: [],
        analyzeFuncData: [],
        selectedLinkType: {},
        protocolForm: {},
        protocolFormRules: {
          linkTypes: [
            {required: true, message: '请选择链路类型', trigger: 'blur'}
          ],
          deviceType: [
            {required: true, message: '请选择设备类别', trigger: 'blur'}
          ],
          // manufacturer: [
          //   {required: true, message: '请选择设备厂家', trigger: 'blur'}
          // ],
          protocolName: [
            {required: true, message: '请填写协议名称', trigger: 'blur'}
          ],
          protocolVer: [
            {required: true, message: '请填写协议版本', trigger: 'blur'}
          ],
          devices: [
            {required: true, message: '请选择关联的设备集合', trigger: 'blur'}
          ],
          generalProtocolId: [
            {required: true, message: '请选择关联的通用协议', trigger: 'blur'}
          ],
        },
        protocolFormRef: 'protocolFormRef',
        isEditProtocol: false,
        isCopyProtocol: false,
        showDocumentDialog: false,
        protocolFiles: [],
        protocolFilesTotal: 0,
        showDocumentUploadDialog: false,
        action: `${assetBaseUrl}/protocol/file/upload`,
        deviceType: '',
        protocolId: '',
        protocolList: {},
        uploadHeader: {
          'token': getUserInfo().token,
          'userId': getUserInfo().userId

        },
        fileList: [],
        defaultSort: {prop: 'date', order: 'ascending'},
        // 存储当前要取消的请求
        source: [],
        // 存储请求的数组
        requestArr: [],
        delFileList: [],
        myLoading: '',
        uploadLoading: false,
        generalProtocolData: [],
        showProtocolWidgetDialog: false,
        showRelatedProtocolWidgetDialog: false,
        relatedProtocolForm: {
          generalProtocolId: ''
        },
        relatedProtocolFormRules: {
          generalProtocolId: [
            {required: true, message: '请选择通用协议', trigger: ['blur', 'change']}
          ],
        },
        relatedProtocolFormRef: 'relatedProtocolFormRef',
        protocolTypeArray: [],
        curDeviceProtocolId: '',
        curGenDeviceType: '',
        relatedProtocolLoading: false,
        activeName: 0,
        currentGeneralProtocolId: '',
        protocolVersionData:[
          {label: '3.1', value: '3.1'},
          {label: '3.1.1', value: '3.1.1'},
          {label: '5', value: '5'},
        ]
      }
    },
    computed: {
      formTitle() {
        return `${this.isCopyProtocol ? '复制' : this.isEditProtocol ? '编辑' : '新增'}协议`
      },
      showUnpackItem() {
        return (unpackTypes) => {
          const idx = commonConfig.unpackType.findIndex(type => {
            return type.value === this.protocolForm.specialConfig.unpackType;
          });
          return unpackTypes.includes(idx);
        }
      },
      protocolOptData() {
        return [
          {
            type: 'btn',
            label: '新增协议',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initProtocolForm();
      this.getDeviceTypeData();
      this.getManufacturerData();
      this.getLinkTypeData();
      this.getProtocolTypeData();
      this.getAnalyzeFuncData();
      this.getProtocolData();
    },

    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, protocolTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const protocol = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showProtocolDialog = true;
              this.isEditProtocol = true;
              this.isCopyProtocol = false;
              this.protocolForm = protocol;
              this.protocolForm.retryInterval = this.protocolForm.retryInterval ? this.protocolForm.retryInterval : 10000
              this.getGeneralProtocolData(protocol.deviceType);
              this.activeName = protocol.linkTypeNames[0] || 0
              break;
            case tableOptBtnConfig.copy.type:
              this.showProtocolDialog = true;
              this.isCopyProtocol = true;
              this.isEditProtocol = false;
              this.protocolForm = protocol;
              this.protocolForm.retryInterval = this.protocolForm.retryInterval ? this.protocolForm.retryInterval : 10000
              this.getGeneralProtocolData(protocol.deviceType);
              // this.linkTypeChanged(protocol.linkType);
              break;
            case tableOptBtnConfig.command.type:
              this.$router.push({
                name: routerMeta.command.name,
                params: {pid: protocol._id}
              });
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteProtocol(protocol);
              break;
            case tableOptBtnConfig.upload.type:
              this.showDocumentDialog = true
              this.protocolList = data
              this.protocolId = data._id
              this.protocolFilesList(data._id)
              // if (data.protocolFiles) {
              //   this.protocolFiles = data.protocolFiles
              //   this.protocolFilesTotal = data.protocolFiles.length > 0 ? data.protocolFiles.length : 0
              // } else {
              //   this.protocolFiles = []
              //   this.protocolFilesTotal = 0
              // }
              break;
            case tableOptBtnConfig.widgetList.type:
              this.curDeviceProtocolId = protocol._id
              this.curGenDeviceType = protocol.deviceType
              this.currentGeneralProtocolId = protocol.generalProtocolId
              this.showProtocolWidgetDialog = true;
              break;
            case tableOptBtnConfig.relateProtocol.type:
              this.showRelatedProtocolWidgetDialog = true;
              this.relatedProtocolForm.generalProtocolId = protocol.generalProtocolId || ''
              this.protocolId = protocol._id
              this.getGeneralProtocolData(protocol.deviceType);
              break;

            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initProtocolForm() {
        this.protocolForm = {
          deviceType: '',
          manufacturer: '',
          linkTypes: [],
          protocolType: '',
          protocolName: '',
          deviceChannel: 1,
          protocolParams: [],
          collectWay: 'async',
          specialConfig: {
            addrCharStartPos: 0,
            addrCharLength: 0,
            unpackType: '',
            delimiter: '',
            startChar: '',
            lenCharStartPos: 0,
            lenCharLength: 0,
            encodeType: 0,
            computedDataStartPos: 0,
            terminatorRelPos: 0,
          },
          minCollectInterval: 5000,
          retryInterval: 10000,
          protocolVer: 'v1.0.0',
          devices: [],
          remarks: '',
          generalProtocolId: '',
          protocolMark: 1,
        };
      },
      resetProtocolForm() {
        this.initProtocolForm();
        const protocolForm = this.$refs[this.protocolFormRef];
        protocolForm && protocolForm.resetFields();
      },
      clickCreateBtn() {
        (this.isEditProtocol || this.isCopyProtocol) && this.resetProtocolForm();
        this.showProtocolDialog = true;
        this.isEditProtocol = false;
        this.isCopyProtocol = false;
      },
      getDeviceTypeData() {
        API.deviceType.deviceTypeAll().then(result => {
          const {data = []} = result;
          this.deviceTypeData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getManufacturerData() {
        API.manufacturer.manufacturerAll().then(result => {
          const {data = []} = result;
          this.manufacturerData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getLinkTypeData() {
        API.linkType.linkTypeAll().then(result => {
          const {data = []} = result;
          this.linkTypeData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      linkTypeChanged(val) {
        const resultArray = val.map(id => {
          const foundObject = this.linkTypeData.find(obj => obj._id === id);  console.log(222,foundObject)
          return foundObject ? {linkType: foundObject._id, linkTypeName: foundObject.name} : null;
        }).filter(item => item !== null); // 过滤掉未找到的项

          const bMap = new Map( this.protocolForm.protocolParams.map(item => [item.linkType, item]));
          resultArray.forEach((itemA, index) => {
            const matchedItemB = bMap.get(itemA.linkType);
            // 如果存在匹配项，则更新a中的对象
            if (matchedItemB) {
              resultArray[index] = { ...itemA, ...matchedItemB }; // 合并两个对象，b中的属性会覆盖a中的同名属性
            }
          });
          this.protocolForm.protocolParams = resultArray
           this.activeName = resultArray[0].linkTypeName
      },
      getProtocolTypeData() {
        API.protocolType.protocolTypeAll().then(result => {
          const {data = []} = result;
          this.protocolTypeData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getAnalyzeFuncData() {
        API.analyzeFunc.analyzeFuncAll().then(result => {
          const {data = []} = result;
          this.analyzeFuncData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      deviceTypeChanged(val) {
        this.protocolForm.generalProtocolId=''
        this.getGeneralProtocolData(val);
      },
      getGeneralProtocolData(deviceType) {
        const filters = [{key: 'deviceType', value: [deviceType], fieldType: "string"}];
        API.generalProtocol.generalProtocolList({filters}).then(result => {
          const {data = []} = result;
          this.generalProtocolData = data;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      getProtocolData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.protocol.protocolList({selector, ...tableParam}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.protocolData = data.map(d => {
            return {
              ...d,
              linkTypeName: d.linkTypeNames.join(','),
              protocolMarkText: d.protocolMark === 1 ? '常规' : d.protocolMark === 2 ?'特定':'--',
            };
          });
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      deleteProtocol(protocol = {}) {
        confirmHandle({label: `确定要删除设备协议：${protocol.protocolName} 吗?`}).then(() => {
          API.protocol.protocolDelete({_id: protocol._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '设备协议'});
            this.tableHdl.judgeTableMatched();
            this.getProtocolData();
            this.resetProtocolForm();
          });
        }).catch(() => {
        });
      },
      protocolFormCanceled() {
        this.showProtocolDialog = false;
      },
      protocolFormSubmitted() {
        this.$refs[this.protocolFormRef].validate((valid) => {
          if (!valid) return;
          if (!this.checkAllValuesNonEmpty(this.protocolForm.protocolParams)) {
            this.$message.warning('请填写完整的链路类型参数');
            return false;
          }
          this.protocolFormLoading = true;
          delete this.protocolForm.linkType
          delete this.protocolForm.protocolParam
          if (this.isCopyProtocol) {
            API.protocol.protocolClone({...this.protocolForm}).then(result => {
              messageHandle({code: msgCode.COPY_SUCCESS, title: '设备协议'});
              this.showProtocolDialog = false;
              this.protocolFormLoading = false;
              this.getProtocolData();
              this.resetProtocolForm();
            }).catch(err => {
              console.log('err', err)
              this.protocolFormLoading = false;
            });
          } else {
            if (this.isEditProtocol) {
              API.protocol.protocolEdit({...this.protocolForm}).then(result => {
                messageHandle({code: msgCode.EDIT_SUCCESS, title: '设备协议'});
                this.showProtocolDialog = false;
                this.protocolFormLoading = false;
                this.getProtocolData();
                this.resetProtocolForm();
              }).catch(err => {
                console.log('err', err)
                this.protocolFormLoading = false;
              });
            } else {
              API.protocol.protocolAdd({...this.protocolForm}).then(result => {
                messageHandle({code: msgCode.ADD_SUCCESS, title: '设备协议'});
                this.showProtocolDialog = false;
                this.protocolFormLoading = false;
                this.getProtocolData();
                this.resetProtocolForm();
              }).catch(err => {
                console.log('err', err)
                this.protocolFormLoading = false;
              });
            }
          }
        });
      },
      protocolFilesList(id) {
        API.protocol.protocolFilesList({_id: id}).then(result => {
          this.protocolFiles = result.data
          this.protocolFilesTotal = result.data.length
        }).catch(err => {
          console.log('err', err)

        });
      },
      transFormTime(val) {
        if (val) {
          return moment(val).format(momentFormat.dateTimeDetail)
        }
      },
      deletFiles(row) {
        confirmHandle({label: `是否要删除：${row.name} 协议文档吗?`}).then(() => {
          // this.getProtocolData()
          API.protocol.protocolUploadDelete({fileName: row.path, protocolId: this.protocolId}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '设备协议文档'});
            this.protocolFilesList(this.protocolId)
          }).catch(err => {
            console.log('err', err)

          });
        }).catch(() => {
        });
      },

      downloadImage(row) {
        let a = document.createElement('a')
        const fileSuffix = row.path.substring(row.path.lastIndexOf(".") + 1);
        const whiteList = ["pdf"];
        if (whiteList.indexOf(fileSuffix) === -1) {
          window.location.href = `${assetBaseUrl}/file/download/${row.path}`
        } else {
          a.target = "_blank";
          a.href = `${assetBaseUrl}/file/download/${row.path}`
          a.download = row.name
          a.click()
        }
      },

      uploadFiles() {
        this.showDocumentUploadDialog = true
        const category = this.deviceTypeData.find(val => val._id === this.protocolList.deviceType) || {};
        this.deviceType = category.deviceTypeNo

      },
      handleExceed() {
        this.$message.warning(
          `当前限制选择 1 个文件，已选择1个文件`
        );
      },
      handleChange(file, fileList) {
        const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
        const whiteList = ["pdf", "doc", "docx", "xls", "xlsx", 'ppt', 'pptx'];
        if (whiteList.indexOf(fileSuffix) === -1) {
          this.$message.warning('上传文件只能是 pdf、doc、docx、xls、xlsx、ppt、pptx格式');
          fileList.splice(-1, 1)
          return false;
        }
        if (file.size / 1024.0 / 1024.0 > 50) {
          this.$message.warning(`文件大小不能超过50MB，请重新上传`);
          fileList.splice(-1, 1)
          return false;
        }
        this.fileList = fileList;
      },
      handleRemove(file, fileList) {// 删除上传文件
        this.fileList = fileList
      },
      httpUpload() {
        this.uploadLoading = true
        const userInfo = getUserInfo();
        const formData = new FormData();
        formData.append("deviceType", this.deviceType);
        formData.append("protocolId", this.protocolId);
        this.fileList.forEach((file) => {
          formData.append("file", file.raw);
        })
        axios
          .post(this.action, formData, {
            headers: {
              "Content-Type": "multipart/form-data",
              token: userInfo.token || "mockToken",
              userId: userInfo.userId || "mockUserId",
            }
          })
          .then((response) => {
            if (response.data.code === 0) {
              //正确
              this.showDocumentUploadDialog = false
              this.protocolFilesList(this.protocolId)
              this.fileList = []
              this.$message.success(`上传成功`);
              this.uploadLoading = false
            } else {
              //出错
              this.showDocumentUploadDialog = false
              this.uploadLoading = false
              this.$message.error(response.data.errMsg);
            }
          })
          .catch((error) => {
            this.$message.error(`网络错误,请检查网络`);
            this.uploadLoading = false
            console.log(error)
          });
      },
      closeUpload() {
        if (this.fileList.length > 0) {
          this.httpUpload()
        } else {
          this.showDocumentUploadDialog = false
          this.uploadLoading = false
        }

      },
      cancelUpload() {
        this.fileList = []
        this.showDocumentUploadDialog = false
      },
      relatedProtocolWidget() {
        this.$refs[this.relatedProtocolFormRef].validate((valid) => {
          if (!valid) return;
          this.relatedProtocolLoading = true
          const params = {
            protocolId: this.protocolId,
            generalProtocolId: this.relatedProtocolForm.generalProtocolId
          }
          API.generalProtocol.generalProtocolRelated(params).then(result => {
            messageHandle({code: msgCode.COPY_SUCCESS, title: '设备协议关联通用协议小组件'});
            this.showRelatedProtocolWidgetDialog = false;
            this.getProtocolData();
            this.relatedProtocolForm.generalProtocolId = ''
            this.relatedProtocolLoading = false
          }).catch(err => {
            this.relatedProtocolLoading = false
            console.log('err', err)
          });
          // this.showRelatedProtocolWidgetDialog = false
        })

      },
      // 检查数组对象内的每个值是否都不为空
      checkAllValuesNonEmpty(arr) {
        for (const obj of arr) {
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              const value = obj[key];
              if (value === null || value === undefined || value === '') {
                return false; // 如果找到任何一个空值，返回 false
              }
            }
          }
        }
        return true; // 如果所有值都不为空，返回 true
      },
    },
  }
</script>

<style lang="less" scoped>
  /deep/ .el-dialog__body {
    min-height: 300px;
  }

.tab-box{
  width: 90%;
  margin: 0 auto;
}
</style>
